<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-suffix=":">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="标题"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="发布状态" prop="publishStatus">
          <el-select
            v-model="queryParams.publishStatus"
            class="!w-[100px]"
            clearable
            placeholder="全部"
          >
            <el-option :value="0" label="未发布" />
            <el-option :value="1" label="已发布" />
            <el-option :value="-1" label="已撤回" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="flex flex-col h-full" body-style="height: calc(100% - 50px);">
      <template #header>
        <el-button
          v-hasPerm="['sys:notice:add']"
          type="success"
          icon="plus"
          @click="handleOpenDialog()"
        >
          新增消息
        </el-button>
        <el-button
          v-hasPerm="['sys:notice:delete']"
          type="danger"
          :disabled="selectIds.length === 0"
          icon="delete"
          @click="handleDelete()"
        >
          删除
        </el-button>
      </template>

      <base-page-table
        :table-data="pageData"
        :table-columns-data="tableColumnsData"
        :loading="loading"
        :page-num="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        class="h-full"
        @selection-change="handleSelectionChange"
        @handleQuery="handlePageChange"
      >
        <template #type="{ row, name }">
          {{ getLabelByValue(MESSAGE_TYPE_ENUM, row.type) }}
        </template>
        <template #level="{ row, name }">
          <el-tag :type="MESSAGE_LEVEL_ENUM_MAP[row.level] || 'primary'">
            {{ getLabelByValue(MESSAGE_LEVEL_ENUM, row.level) }}
          </el-tag>
        </template>
        <template #isRead="{ row, name }">
          <el-tag v-if="row.isRead == 1" type="success">已读</el-tag>
          <el-tag v-else type="info">未读</el-tag>
        </template>
        <template #targetType="scope">
          {{ getLabelByValue(TARGET_TYPE_ENUM, scope.row.targetType) }}
        </template>
        <template #publishStatus="scope">
          <el-tag v-if="scope.row.publishStatus == 0" type="info">未发布</el-tag>
          <el-tag v-if="scope.row.publishStatus == 1" type="success">已发布</el-tag>
          <el-tag v-if="scope.row.publishStatus == -1" type="warning">已撤回</el-tag>
        </template>
        <template #createTime="scope">
          <div class="flex-x-start">
            <span>创建时间：</span>
            <span>{{ scope.row.createTime || "-" }}</span>
          </div>

          <div v-if="scope.row.publishStatus === 1" class="flex-x-start">
            <span>发布时间：</span>
            <span>{{ scope.row.fmtPublishTime || "-" }}</span>
          </div>
          <div v-else-if="scope.row.publishStatus === -1" class="flex-x-start">
            <span>撤回时间：</span>
            <span>{{ scope.row.revokeTime || "-" }}</span>
          </div>
        </template>
        <template #handle="scope">
          <el-button
            type="primary"
            size="small"
            link
            @click="handleOpenNoticeDetailDialog(scope.row.id)"
          >
            查看
          </el-button>
          <el-button
            v-if="scope.row.publishStatus != 1"
            v-hasPerm="['sys:notice:publish']"
            type="primary"
            size="small"
            link
            @click="handlePublish(scope.row.id)"
          >
            发布
          </el-button>
          <el-button
            v-if="scope.row.publishStatus == 1"
            v-hasPerm="['sys:notice:revoke']"
            type="primary"
            size="small"
            link
            @click="handleRevoke(scope.row.id)"
          >
            撤回
          </el-button>
          <el-button
            v-if="scope.row.publishStatus != 1"
            v-hasPerm="['sys:notice:edit']"
            type="primary"
            size="small"
            link
            @click="handleOpenDialog(scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.publishStatus != 1"
            v-hasPerm="['sys:notice:delete']"
            type="danger"
            size="small"
            link
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </base-page-table>
    </el-card>

    <!-- 消息公告表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      top="4vh"
      width="1250"
      destroy-on-close
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="formData.title" placeholder="消息标题" clearable />
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <WangEditor v-model="formData.content" />
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="formData.type" search placeholder="请选择消息类型">
            <el-option
              v-for="item in messageTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消息等级" prop="level">
          <el-select v-model="formData.level" search placeholder="请选择消息等级">
            <el-option
              v-for="item in messageLevelList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标类型" prop="targetType">
          <el-radio-group v-model="formData.targetType" @change="handleTargetTypeChange">
            <el-radio :value="item.value" v-for="(item, index) in targetTypeList" :key="index">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="formData.targetType == TARGET_TYPE_ENUM.CUSTOM.value"
          label="指定用户"
          prop="targetUserIds"
        >
          <el-button @click="handleOpenSelectUserDialog()">
            选择用户（已选择{{ formData.targetUsers?.length }}）
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()" :loading="loading">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 消息公告详情 -->
    <NoticeDetail ref="noticeDetailRef" />
    <select-user ref="selectUserRef" @select-user="handleSelectUser"></select-user>
  </div>
</template>

<script setup lang="ts">
import { getLabelByValue, getLabelValueList } from "@/utils/enums";
defineOptions({
  name: "Notice",
  inheritAttrs: false,
});

import NoticeAPI, { NoticePageVO, NoticeForm, NoticePageQuery } from "@/api/system/notice";
import UserAPI from "@/api/system/user";
import {
  MESSAGE_LEVEL_ENUM,
  MESSAGE_LEVEL_ENUM_MAP,
  MESSAGE_TYPE_ENUM,
  TARGET_TYPE_ENUM,
} from "@/enums/notice/NoticeEnum";
import { TRANSACTION_TYPE_ENUM } from "@/enums/conins/ConinsEnum";
import SelectUser from "@/views/system/notice/components/select-user.vue";

const queryFormRef = ref();
const dataFormRef = ref();
const noticeDetailRef = ref();
const selectUserRef = ref();

const loading = ref(false);
const selectIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<NoticePageQuery>({
  pageNum: 1,
  pageSize: 10,
});
const targetTypeList = getLabelValueList(TARGET_TYPE_ENUM);
const messageTypeList = getLabelValueList(MESSAGE_TYPE_ENUM);
const messageLevelList = getLabelValueList(MESSAGE_LEVEL_ENUM);

const userOptions = ref<OptionType[]>([]);
// 消息公告表格数据
const pageData = ref<NoticePageVO[]>([]);
const tableColumnsData = ref([
  { type: "selection", width: 50, align: "center" },
  {
    type: "index",
    label: "序号",
    width: 60,

    align: "center",
  },
  {
    label: "标题",
    prop: "title",
    align: "center",
    showOverflowTooltip: true,
  },
  {
    label: "消息类型",
    width: 150,
    align: "center",
    showOverflowTooltip: true,
    customSlot: "type",
  },
  {
    label: "发布人",
    width: 150,
    align: "center",
    showOverflowTooltip: true,
    prop: "publisherName",
  },
  {
    width: 150,
    label: "紧急程度",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "level",
  },
  {
    width: 150,
    label: "目标类型",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "targetType",
  },
  {
    width: 150,
    label: "发布状态",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "publishStatus",
  },
  {
    width: 250,
    label: "操作时间",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "createTime",
  },
  {
    width: 200,
    label: "操作",
    prop: "handle",
    fixed: "right",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "handle",
  },
]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 消息公告表单数据
const formData = reactive<NoticeForm>({
  level: MESSAGE_LEVEL_ENUM.NORMAL.value, // 默认优先级为低
  targetType: 1, // 默认目标类型为全体
  targetUsers: [], // 默认目标类型为全体
});

// 消息公告表单校验规则
const rules = reactive({
  title: [{ required: true, message: "请输入消息标题", trigger: "blur" }],
  content: [
    {
      required: true,
      message: "请输入消息内容",
      trigger: "blur",
      validator: (rule: any, value: string, callback: any) => {
        if (!value.replace(/<[^>]+>/g, "").trim()) {
          callback(new Error("请输入消息内容"));
        } else {
          callback();
        }
      },
    },
  ],
  type: [{ required: true, message: "请选择消息类型", trigger: "change" }],
});

// 查询消息公告
function handleQuery() {
  loading.value = true;
  NoticeAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handlePageChange(val) {
  queryParams.pageNum = val.pageNum;
  queryParams.pageSize = val.pageSize;
  handleQuery();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 行复选框选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

// 打开消息公告弹窗
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改消息";
    NoticeAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    Object.assign(formData, {
      level: MESSAGE_LEVEL_ENUM.NORMAL.value,
      targetType: TARGET_TYPE_ENUM.ALL.value,
      targetUsers: [], // 默认目标类型为全体
      content: "", // 默认目标类型为全体
    });
    dialog.title = "新增消息";
  }
}

// 发布消息公告
function handlePublish(id: number) {
  NoticeAPI.publish({
    noticeId: id,
  }).then(() => {
    ElMessage.success("发布成功");
    handleQuery();
  });
}

// 撤回消息公告
function handleRevoke(id: number) {
  NoticeAPI.revoke({
    noticeId: id,
  }).then(() => {
    ElMessage.success("撤回成功");
    handleQuery();
  });
}

function handleTargetTypeChange(val) {
  if (val === TARGET_TYPE_ENUM.CUSTOM.value) {
    handleOpenSelectUserDialog();
  }
}
function handleOpenSelectUserDialog(val) {
  selectUserRef.value.showModal(formData.targetUsers);
}

// 消息公告表单提交
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        NoticeAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        NoticeAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 重置表单
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
  formData.targetType = 1;
}

// 关闭消息公告弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

// 删除消息公告
function handleDelete(id?: number) {
  const deleteIds = id ? [id] : selectIds.value;
  if (!deleteIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      NoticeAPI.deleteByIds(deleteIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开消息公告详情弹窗
function handleOpenNoticeDetailDialog(id: number) {
  noticeDetailRef.value.openNotice(id);
}
function handleSelectUser(selection: any) {
  formData.targetUsers = selection.map((item: any) => {
    return {
      id: item.userId,
      terminal: item.userTerminal,
      nickName: item.nickname,
    };
  });
}

onMounted(() => {
  handleQuery();
});
</script>
